package sky.cin.framework.nio;

import java.io.IOException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Set;

public class SyncableSelector {

    private Selector selector;
    private volatile boolean flag;

    public SyncableSelector(Selector selector) {
        this.selector = selector;
    }

    public static SyncableSelector open() {
        Selector open = null;
        try {
            open = Selector.open();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new SyncableSelector(open);
    }

    public Selector instance() {
        return selector;
    }

    public synchronized SelectionKey register(SelectableChannel channel, int op) {
        try {
            flag = true;
            selector.wakeup();
            channel.configureBlocking(false);
            SelectionKey register = channel.register(selector, op);
            flag = false;
            return register;
        } catch (ClosedChannelException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public int select() throws IOException {
        while (flag);
        return selector.select();
    }

    public Set<SelectionKey> selectedKeys() {
        return selector.selectedKeys();
    }
}
